package com.xxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.dto.DepartmentDto;
import com.xxx.pojo.Department;
import com.xxx.pojo.User;
import com.xxx.reportingsystem.service.UserService;
import com.xxx.service.DepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/department")
public class DepartmentController {


    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private UserService userService;

    /**
     * 新增部门
     * @param department
     * @return
     */
    @Transactional
    @PostMapping("/save")
    @PreAuthorize("hasAnyAuthority('sys:add:department')")
    public Result save(@RequestBody Department department){
        LocalDateTime now = LocalDateTime.now();
        department.setUpdateDate(now);

        log.info("department:{}",department);
        boolean save = departmentService.save(department);
        return save ? Result.success("添加成功") : Result.error("保存失败");
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional
    @DeleteMapping("/del/{id}")
    @PreAuthorize("hasAnyAuthority('sys:delete:department')")
    public Result delById(@PathVariable Integer id){
        boolean remove = departmentService.removeById(id);
        return remove ? Result.success("删除成功") : Result.error("删除失败");
    }


    /**
     * 修改部门
     * @param department
     * @return
     */
    @Transactional
    @PutMapping("/update")
    @PreAuthorize("hasAnyAuthority('sys:update:department')")
    public Result updateById(@RequestBody Department department){

        LocalDateTime now = LocalDateTime.now();
        department.setUpdateDate(now);
        boolean update = departmentService.updateById(department);
        return update ? Result.success("更新成功") : Result.error("更新失败");
    }

    @GetMapping("/get-department")
    @PreAuthorize("hasAnyAuthority('sys:select:department')")
    public Result getDepartment(Integer pageNo,Integer pageSize,String departmentName,String userName){
        IPage iPage = new Page(pageNo,pageSize);

        Set<Integer> set = null;
        if(userName != null){
            List<User> userList = userService.list(new LambdaQueryWrapper<User>().like(User::getName, userName));
            set = userList.stream().map(User::getDepartmentId).collect(Collectors.toSet());
        }


        iPage = departmentService.page(iPage, new LambdaQueryWrapper<Department>()
                .like(departmentName != null && departmentName.trim() != "", Department::getDepartmentName, departmentName)
                .in(set != null, Department::getId, set));

        List<Department> records = iPage.getRecords();

        List<DepartmentDto> departmentDtoList = records.stream().map(department -> {
            DepartmentDto departmentDto = new DepartmentDto();
            BeanUtils.copyProperties(department, departmentDto);
//            User user = userService.getById(department.getCharge());
            List<User> users = userService.list(new LambdaQueryWrapper<User>().eq(User::getDepartmentId, department.getId()));

            users = users.stream().filter(user -> {
                if (department.getCharge().equals(user.getUserId().longValue())){
                    departmentDto.setChargeUser(user);
                    return false;
                }
                else
                    return true;
            }).collect(Collectors.toList());

            departmentDto.setUserList(users);
//            departmentDto.setChargeUser(user);

            return departmentDto;
        }).collect(Collectors.toList());

        iPage.setRecords(departmentDtoList);
        return Result.success("查询成功",iPage);
    }

}